package com.google.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public abstract class Page {
	
	protected static final String baseURL = "http://www.google.com";
	protected static final String menuItemsXpath = "//ol[@id='gbzc']/li[@class='gbt']/a";
	protected static final String submenuItemsXpath = "//li[@class='gbmtc']/a[@class='gbmt']";
		
	protected WebDriver driver;
	
	public Page (WebDriver driver) {
		this.driver = driver;
	}
	
	public abstract void open ();
	
	public boolean isSubmenuPresent () {
		try {
			driver.findElement(By.xpath(submenuItemsXpath));
		} catch (NoSuchElementException e) {
			return false;
		}
		return true;
	}
	
	public boolean isSubmenuOpened () {
		try {
			if (driver.findElement(By.xpath(submenuItemsXpath)).isDisplayed())
				return true;
			else return false;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
	
	public Page linkClick (WebElement el) {
		try {
			el.click();
		} catch (ElementNotVisibleException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return PageFactory.initElements(driver, Page.class);
	}
	
	public String getTitle () throws InterruptedException {
		new WebDriverWait(driver, 10).until(new ExpectedCondition<Boolean>() {
			public Boolean apply(WebDriver d) {
				return d.getTitle().length()>5;
			}
		});
		return driver.getTitle();
	}
	
	public void back () {
		driver.navigate().back();
		//return PageFactory.initElements(driver, HomePage.class);
	}
	
	public boolean isTextPresent(String text) throws NoSuchElementException {
		try {
			driver.findElement(By.xpath("//*[text()='" + text + "']"));
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
	
	protected void completeField (WebElement el, String value) {
		el.clear();
		el.sendKeys(value);
		if (!el.getAttribute("value").equals(value)) completeField(el, value);
	}
	
	public boolean isElementVisible(WebElement el) {
		try {
			return el.isDisplayed();
		} catch (NoSuchElementException e) {
			return false;
		}
	}


}
